package com.library.filter;


import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

@Component
@Order(1)
public class AuthFilter implements Filter {
    private static final Set<String> WHITE_LIST=new HashSet(Arrays.asList("/","/home","/login"));
    private static final Set<String> Admin_LIST=new HashSet(Arrays.asList(
            "/adminList","/userList","/bookEdit","/borrowList"));//管理员权限访问地址

    @Override
    public void init(FilterConfig filterConfig){}

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain)throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest) request;
        HttpServletResponse resp=(HttpServletResponse) response;
        String requestURI=req.getRequestURI();
        String ctx=req.getContextPath();
        String path=requestURI.substring(ctx.length());

        //白名单放行
        if ((isWhiteListed(requestURI))){
            chain.doFilter(req, resp);
            return;
        }

        //检查是否登录
        HttpSession session=req.getSession();//获取session
        if (session==null||session.getAttribute("role")==null){
           resp.sendRedirect(req.getContextPath()+"/login");
           return;
        }

        //普通地址访问
        if(!isAdminListed(path)){
            chain.doFilter(req, resp);
            return;
        }

        //管理员地址访问
        if(session.getAttribute("role")!="admin"){
            resp.sendRedirect(req.getContextPath()+"/login");//返回登录并要求管理员登录
            session.setAttribute("msg","not admin");
            return;
        }

        chain.doFilter(req,resp);
    }

    /**
     *
     * @param uri 要访问的地址
     * @return 是否在白名单内，true在白名单，false不在
     */
    private boolean isWhiteListed(String uri){
        return WHITE_LIST.contains(uri);
    }//检查是否在白名单内

    /**
     *
     * @param uri 请求地址
     * @return 是否在管理员权限地址中
     */
    private boolean isAdminListed(String uri){return Admin_LIST.contains(uri);}

    @Override
    public void destroy(){}
}
